from multiprocessing import Process, Pool
from threading import Thread
import requests
import time


def get(url='http://www.baidu.com'):

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    }
    r = requests.get(url=url, headers=headers)
    time.sleep(1)
    print(r.status_code)
    return r.status_code


if __name__ == '__main__':
    start = time.time()
    # 利用Python实现一个多线程程序
    thread_list = []
    for _ in range(5):
        t = Thread(target=get, args=('https://www.zhihu.com',))
        thread_list.append(t)
        t.start()
    [t.join() for t in thread_list]
    end = time.time()
    print(f'多线程耗时：{end - start} s')

    # 将上述多线程程序改为多进程
    process_list = []
    start = time.time()
    for _ in range(5):
        p = Process(target=get, args=('https://www.zhihu.com',))
        process_list.append(p)
        p.start()
    [p.join() for p in process_list]
    end = time.time()
    print(f'多进程耗时：{end - start} s')

    # 多进程使用进程池
    pool = Pool(12)
    start = time.time()
    for _ in range(5):
        pool.apply_async(get, args=('https://www.zhihu.com',))
    pool.close()
    pool.join()
    end = time.time()
    print(f'进程池耗时：{end - start} s')
